package cn.donting.web.desktop.sys.filter;

import cn.donting.web.desktop.core.app.AppGetting;
import cn.donting.web.desktop.core.entity.User;
import cn.donting.web.desktop.sys.service.UserCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;

@Configuration
@Slf4j
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Autowired
    UserCenter userCenter;
    @Autowired
    AppGetting appGetting;

    private HashSet<String> excludeUrl=new HashSet<>();

    public LoginFilter() {
        excludeUrl.add("/sys/user/login");
        excludeUrl.add("/sys/websocket");
        excludeUrl.add("/css/app.50167829.css");
        excludeUrl.add("/css/chunk-vendors.f0c21e17.css");
        excludeUrl.add("/js/app.8efbdc8c.js");
        excludeUrl.add("/js/chunk-vendors.e2d675ef.js");
        excludeUrl.add("/login.html");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) request;
        HttpServletResponse httpServletResponse=(HttpServletResponse) response;
        String requestURI = httpServletRequest.getRequestURI();
        if(excludeUrl.contains(requestURI)){
            chain.doFilter(request,response);
            return;
        }
        User loginUser = userCenter.getLoginUser();
        if(loginUser!=null){
            chain.doFilter(request,response);
            return;
        }
        log.debug("LoginFilter....拦截");
        httpServletResponse.sendRedirect("/login.html?appId=0");
    }
}
